package BanyuanClub.Work.Day0319;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

public class XMLstudents {
    public static void main(String[] args) throws DocumentException, IOException {
        File xmlFile = new File("javase/xml/students.xml");
        SAXReader reader = new SAXReader();
        Document xmlDoc = reader.read(xmlFile);

        Element studentEL = xmlDoc.getRootElement();

        List<Element> studentlist = studentEL.elements();

        //查找并删除 或 修改 ID为*****的元素
        for (Element student :studentlist
             ) {
            if ("10002".equals(student.attributeValue("id"))){
                //删除
//                studentEL.remove(student);
                //修改
                student.element("name").setText("汪汪");
            }
        }

        //替换年龄最大的学生的性别


        //调用方法增加一个学生
//        addStudent(studentEL,"10008","校长","正体不明",100);
        //写文件
        FileWriter fw = new FileWriter("javase/xml/students.xml");
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("UTF-8");
        XMLWriter writer = new XMLWriter(fw,format);
        writer.write(xmlDoc);
        writer.close();

        List<Element> studentlistEL = studentEL.elements();

    }

    //增加一个学生对象方法
    public static void addStudent(Element studentEL,String id,String name,String sex,int age){
        Element stu = studentEL.addElement("student");
        stu.addAttribute("id",id);
        stu.addElement("name").setText(name);
        stu.addElement("sex").setText(sex);
        stu.addElement("age").setText(age+"");

    }
}
